package com.wang.prototype;

import com.wang.enums.Shape;

import java.util.Hashtable;
import java.util.Map;

/**
 * 原型设计模式
 */
public abstract class ShapePrototype implements Cloneable{

    private int id;
    Shape type;
    abstract void draw();

    public Shape getType(){
        return this.type;
    }

    public void setType(Shape type){
        this.type = type;
    }

    public void setId(int id){
        this.id = id;
    }

    @Override
    protected Object clone() {
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        ShapeCache.loadCache();
        ShapePrototype shapePrototype = ShapeCache.getShape(Shape.Rectangle);
        shapePrototype.draw();
        ShapePrototype shapePrototype1 = ShapeCache.getShape(Shape.SQUARE);
        shapePrototype1.draw();
    }
}

class Rectangle extends ShapePrototype{

    public Rectangle(){
        this.type = Shape.Rectangle;
    }

    @Override
    void draw() {
        System.out.println("这是三角形");
    }
}

class Square extends ShapePrototype{

    public Square(){
        this.type = Shape.SQUARE;
    }

    @Override
    void draw() {
        System.out.println("这是矩形");
    }
}

class ShapeCache{
    private static Map<Shape,ShapePrototype> map = new Hashtable<>();

    public static ShapePrototype getShape(Shape shape){
        ShapePrototype shapePrototype = map.get(shape);
        return (ShapePrototype) shapePrototype.clone();
    }

    public static void loadCache(){
        Rectangle rectangle = new Rectangle();
        map.put(Shape.Rectangle,rectangle);

        Square square = new Square();
        map.put(Shape.SQUARE,square);
    }
}
